package com.bishe.book.item.controller;

import com.bishe.book.common.controller.BaseController;
import com.bishe.book.common.domain.FebsResponse;
import com.bishe.book.common.domain.QueryRequest;
import com.bishe.book.common.exception.FebsException;
import com.bishe.book.item.domain.BookBean;
import com.bishe.book.item.domain.ItemBean;
import com.bishe.book.item.domain.UserItemBean;
import com.bishe.book.item.domain.UserLikeItem;
import com.bishe.book.item.service.BookService;
import com.bishe.book.item.service.ItemService;
import com.bishe.book.item.service.UserItemService;
import com.bishe.book.item.service.UserLikeItemService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("item")
public class ItemController extends BaseController {
    private String message;

    @Autowired
    private ItemService itemService;

    @Autowired
    private BookService bookService;

    @Autowired
    private UserItemService userItemService;

    @Autowired
    private UserLikeItemService userLikeItemService;

    @Value("${server.port}")
    private String port;

    @Value("${web.imgIp}")
    private String imgIp;

//    /**
//     * 图书管理列表查询
//     * @param queryRequest
//     * @param itemBean
//     * @return
//     */
//    @GetMapping("item")
//    public Map<String, Object> listItemById(QueryRequest queryRequest, ItemBean itemBean) {
//        return getDataTable(itemService.listItemById(itemBean, queryRequest));
//    }
    /**
     * 图书管理列表查询
     * @param queryRequest
     * @param itemBean
     * @return
     */
    @GetMapping("item/list")
    public Map<String, Object> listItemByName(QueryRequest queryRequest, ItemBean itemBean) {
        return getDataTable(itemService.listItemByName(itemBean, queryRequest));
    }

    /**
     * 通过用户查询相关图书列表
     * @param queryRequest
     * @param itemBean
     * @return
     */
    @GetMapping("user/item")
    public Map<String, Object> listItemByUser(QueryRequest queryRequest, ItemBean itemBean) {
        return getDataTable(itemService.listItemByUser(itemBean, queryRequest));
    }

    /**
     * 查询用户收藏
     * @param queryRequest
     * @param itemBean
     * @return
     */
    @GetMapping("user/like")
    public Map<String, Object> listLikeItem(QueryRequest queryRequest, ItemBean itemBean) {
        return getDataTable(itemService.listLikeItem(itemBean, queryRequest));
    }

//    @GetMapping("itemAll")
//    public List<ItemBean> getItem() {
//        List<ItemBean> list = this.itemService.listItem();
//        return list;
//    }

    /**
     * 校验图书编号，不能重复
     * @param itemid
     * @return
     */
    @GetMapping("check/{itemid}")
    public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String itemid) {
        return this.bookService.getById(itemid) == null;
    }

    /**
     * 新增图书
     * @param bookBean
     * @return
     * @throws FebsException
     */
    @PostMapping
    public FebsResponse save(BookBean bookBean) throws FebsException {
        try {
            message = "新增成功";
            this.bookService.save(bookBean);
            return new FebsResponse().data(message);
        } catch (Exception e) {
            e.printStackTrace();
            message = "新增异常";
            throw new FebsException(message);
        }
    }

    /**
     * 修改图书
     * @param itemBean
     * @throws FebsException
     */
    @PutMapping
    public void updateMenu(@Valid ItemBean itemBean) throws FebsException {
        try {
            this.itemService.updateById(itemBean);
        } catch (Exception e) {
            message = "修改失败";
            throw new FebsException(message);
        }
    }

    /**
     * 删除图书
     * @param itemIds
     * @throws FebsException
     */
    @DeleteMapping("/{itemIds}")
    @Transactional
    public void deleteItems(@NotBlank(message = "{required}") @PathVariable String itemIds) throws FebsException {
        try {
            String[] ids = itemIds.split(StringPool.COMMA);
            this.itemService.removeByIds(Arrays.asList(ids));
        } catch (Exception e) {
            message = "删除菜单/按钮失败";
            throw new FebsException(message);
        }
    }

    /**
     * 列出所有用户信息
     * @return
     */
    @GetMapping("userAll")
    public List<UserItemBean> getUserItem() {
        List<UserItemBean> list = this.userItemService.listUser();
        return list;
    }

    /**
     * 上传图片
     * @param file
     * @return
     * @throws FebsException
     */
    @PostMapping("upload")
    public FebsResponse uploadMessage(@RequestParam("file") MultipartFile file) throws FebsException {
        try {
            String dirPath = System.getProperty("user.dir");
            String newFileName = new Date().getTime() + file.getOriginalFilename();

            String path = File.separator + "uploadImg" + File.separator + newFileName;
            File destFile = new File(dirPath + path);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(destFile);
                // 将相对路径返回给前端
                return new FebsResponse().data("http://" + imgIp + ":" + port + "/img/" + newFileName);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception e) {
            message = "上传图片失败," + e.getMessage();
            throw new FebsException(message);
        }
    }

    /**
     * 添加用户收藏
     * @param userLikeItem
     */
    @PostMapping("addLike")
    public void addLikeItem(UserLikeItem userLikeItem){
        try{
            this.userLikeItemService.save(userLikeItem);
        } catch (Exception e) {
            message = "收藏失败";
            new FebsException(message);
        }
    }

    /**
     * 删除收藏
     * @param userLikeItem
     */
    @DeleteMapping("deleteUserLike")
    public void deleteLikeItem(UserLikeItem userLikeItem){
        try{
            this.userLikeItemService.deleteUserLike(userLikeItem);
        } catch (Exception e) {
            message = "取消失败";
            new FebsException(message);
        }
    }
}
